import utils from '../../utils/util';
import config from '../../config';
Component({
  /**
   * 组件的属性列表
   * 预约才可以使用抵价券 则不需要使用积分
   */
  properties: {
    isShow: {
      type: Boolean,
      value: false
    },
    params: {
      type: Object,
      value: {},
      observer:function(newVal){
        console.log("params",newVal)
      }
    },
    socialRoomId: {
      type: Number,
      default: 0
    },
  },

  lifetimes: {
    attached: function () {
      // this._payType = 0; //0是微信支付，1是余额支付，2是虚拟币支付
      this._userSecret = wx.getStorageSync('userSecret');
      this._companyShare = wx.getStorageSync('companyShare');
      console.log("_companyShare", this._companyShare.companyAuth.companyName,this._userSecret);
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    goodsInfo: {},
    basicInfo: {},
    payConfInfo: {},
    vipInfo: {},
    ckFromDict: config.ckFrom,
    prod_img_dict: config.defaultProdImgDict,
    isCanUseCoupon: false, //是否可以使用优惠券
    isCanUsePoint: false, //是否可以使用积分
    isChooseUsePoint: false, //是否选择使用积分抵扣
    vipDisPriceInfo: "",
    totalPrice: 0,
    isVipPay: false, //是否vip支付
    chooseCouponInfo: null, //选中优惠券的价格
    chooseCouponPrice: 0, //优惠券减少的金额
    isShowCouponList: false,
    pointDiscountText: "",
    isShowDiscount: false,
    isChooseAgreement:true
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onOpen() {
      let params = this.data.params;
      let otherParams = params.otherParams;
      this._companyShare = wx.getStorageSync('companyShare');
      console.log("open",this.data.params)
      //有商品信息,说明是虚拟商品下单，反之就是直接下单（类似打赏这种）
      if(params.goods){
        let isVipPay = otherParams.prodType == config.ckFrom.svip || otherParams.prodType == config.ckFrom.vip || otherParams.prodType == config.ckFrom.collageVip || otherParams.prodType == config.ckFrom.collageSvip;
      this.data.goodsInfo =params.goods.length ? params.goods[0] : [];
      this.data.basicInfo = params.basic;
      this.data.payConfInfo = params.payConf;
      this.data.vipInfo = params.vip;
      this.vipDiscountInfo={};
      let proPrice = Number(this.data.goodsInfo.price).toFixed(2);
      let vipDisPriceInfo = this.getVipDisPriceInfo();
      let isCanUseCoupon = this.isCanUseCoupon(proPrice);
      let isCanUsePoint = this.isCanUsePoint(proPrice);
      console.log("this.data.goodsInfo",this.data.goodsInfo)
      this.setData({
        chooseCouponPrice: 0, //优惠券减少的金额
        chooseCouponInfo:"",
        isVipPay: isVipPay,
        goodsInfo: this.data.goodsInfo,
        basicInfo:  this.data.basicInfo ,
        payConfInfo: this.data.payConfInfo,
        vipInfo:  this.data.vipInfo,
        isCanUseCoupon: isCanUseCoupon,
        isCanUsePoint: isCanUsePoint,
        vipDisPriceInfo: vipDisPriceInfo,
        totalPrice: proPrice,
        pointDiscountText:"",
      },()=>{
        this.calcProPrice();
      })
      }else{
        if(otherParams.fromType == 1){
          //打赏类型
          this.setData({
            totalPrice:otherParams.totalPrice
          })
        }
      }
      
    },
    toggleAgreement(){
      this.setData({
        isChooseAgreement:!this.data.isChooseAgreement
      })
    },
    switchUsePoint(e) {
      console.log(e)
      let val = e.detail.value;
      this.setData({
        isChooseUsePoint: val
      },()=>{
        this.calcProPrice();
      })
    },
    getOrderId() {
      // this._payType = Number(this.data.totalPirce) == 0 ? 1 : 0;
      let showExpire= false;
      let sendData={};
      if(this._companyShare.companyAuth.expireTime){
        showExpire = (utils.getTimeByDate(this._companyShare.companyAuth.expireTime) - (new Date()).getTime()) < 0 ? true :false;
      }
      if (showExpire) {
        wx.showToast({
          title: '打烊期间无法购买商品，已购用户可以继续访问已购内容！',
        })
        return;
      }
      if(!this.data.isChooseAgreement){
        wx.showToast({
          title: '请先勾选协议！',
          icon:"none"
        })
        return;
      }
      if(this._orderSubmiting) return;
      this._orderSubmiting=true;
      if(this.data.params.goods){
        //
        sendData = this.getProSubmitData();
      }else{
        sendData = this.getRewardSubmitData();
      }
      utils.post('orders/submitOrder', sendData).then((res) => {
        if (res.orderId == -1) {
          this._orderSubmiting= false;
          wx.showModal({
            title: '提示',
            content: '订单提交失败，请重新提交！',
            showCancel: false,
            confirmText: "我知道"
          }) 
        } else if (res.code == 201) {
          this._orderSubmiting= false;
          wx.showToast({
            title: '支付成功',
            icon: "success"
          })
          this.triggerEvent("paySuccess")
        } else {
          console.log("this._userSecret", this._userSecret)
          utils.post("payment/wxpayConf", {
            openid: this._userSecret.openId,
            orderId: res.orderId
          }).then(resData => {
            this.setData({
              isShow:false
            })
            wx.navigateTo({
              url: '/pages/commerce-pay/index',
              success: (res) => {
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                  timeStamp: resData.data.timeStamp,
                  nonceStr: resData.data.nonceStr,
                  package: resData.data.package,
                  signType: resData.data.signType,
                  paySign: resData.data.paySign
                })
              },
              complete:()=>{
                this._orderSubmiting= false;
              }
            });
          }).catch(()=>{
            this._orderSubmiting= false;
          })
        }
      }).catch(()=>{
        this._orderSubmiting= false;
      })
    },

    //获取虚拟商品提交数据
    getProSubmitData(){
      let couponType = 1;
      let otherParams = this.data.params.otherParams;
      this.data.basicInfo.coupon.enable.forEach(item => {
        if (item.rcdId == this.data.chooseCouponInfo.rcdId) {
          couponType = item.couponType;
        }
      })
      let sendData = {
        extGroupId: '', //分销拼团groupId
        isCaptain: '', //分销拼团 1 是团长 0 不是
        companyId: '', //分销的内容方id
        collageId: '',
        groupId: '',
        fromInvite: 0,
        inviteId: -1, //社群邀请人ID，用来绑定邀请进社群的关系
        prodId: otherParams.extId == -1 ? otherParams.cId : otherParams.extId,
        useCoupon:this.data.chooseCouponInfo ? this.data.chooseCouponInfo.rcdId : -1,
        usePoint: this.data.isChooseUsePoint,
        payMoney: Number(this.data.totalPrice).toFixed(2),
        payMethod: 1,
        prodType: otherParams.prodType,
        couponType: couponType,
        subProdId: this.data.socialRoomId,
        subProdType: config.ckFrom.live
      };
      if (this.data.detailId) {
        //独立直播间
        sendData.detailId = this.data.detailId;
      }
      if(otherParams.aaId){
        //服务商购买升级
        sendData.aaId = otherParams.aaId;
      }
      if (otherParams.relationType == config.relationTypeMap.flashSales) {
        // 来自限时购
        sendData.groupId =otherParams.extraId
        sendData.mtkType = 1;
      }
      if(otherParams.prodType == config.ckFrom.valuableCoupon){
        //有价券
        sendData.groupId = otherParams.extId;
        sendData.prodId = this.data.params.goods[0].rcdId
      }
      console.log("getProSubmitData",sendData)
      return sendData;
    },
    initRewardParams(data){
      this.setData({
        params:data,
        totalPrice:data.otherParams.totalPrice
      })
    },
    //获取打赏提交的数据
    getRewardSubmitData(){
      let otherParams = this.data.params.otherParams;
      let sendData = {
        fromInvite: 0,
        usePoint: false,
        useCoupon:-1,
        prodType:35, //直播35
        inviteId: -1, //社群邀请人ID，用来绑定邀请进社群的关系
        payMethod:1,
        number: otherParams.number || 1,
        prodId:this.data.socialRoomId,
        groupId:otherParams.groupId,
        payMoney: Number(this.data.totalPrice).toFixed(2),
      }
      if(otherParams.subSonProdId){
        sendData.subSonProdId = otherParams.subSonProdId;
      }
      if(otherParams.lgcId){
        //打赏礼物的时候才有
        sendData.lgcId = otherParams.lgcId;
      }
      console.log("getRewardSubmitData",sendData)
      return sendData;
    },

    getPayShow(data) {
      return new Promise(resolve => {
        utils.get("common/payShow", data).then(res => {
          this.setData({
            goodsInfo: res.goods.length ? res.goods[0] : [],
            basicInfo: res.basic,
            payConfInfo: res.payConf,
            vipInfo: res.vip
          }, () => {
            resolve();
          })
        })
      })
    },
    //计算总价格
    calcProPrice() {
      let price = Number(this.data.goodsInfo.price).toFixed(2);
      price = this.getAfterVipDiscountPrice(price);
      price = this.getAfterCouponPrice(price);
      price = this.getAfterPointsPrice(price);
      this.setData({
        totalPrice: price
      })
    },
    //获取vip折扣后的价格
    getAfterVipDiscountPrice(price) {
      let vipInfo = this.data.vipDisPriceInfo;
      if (vipInfo && vipInfo.vipType) {
        if (vipInfo.dpType == 1) {
          price = price * vipInfo.dpVal / 100
        } else {
          price = vipInfo.dpVal
        }
      }
      price = Number(price) > 0 ? Number(price).toFixed(2) : '0.00';
      console.log("getAfterVipDiscountPrice", `price:${price}`)
      return price;
    },
    //使用优惠券后的价格
    getAfterCouponPrice(price) {
      console.log("getAfterCouponPrice",typeof(price))
      let info = this.data.chooseCouponInfo;
      let chooseCouponPrice = this.data.chooseCouponPrice;
      if (info) {
        let ckFrom = this.data.ckFrom;
        let ckFromDict = config.ckFrom;
        if (info.type == 4) {
          if (ckFrom == ckFromDict.booking) {
            price = 0;
            chooseCouponPrice = 0;
          }
        } else if (info.type == 5) {
          //折扣
          chooseCouponPrice =  (1 - (info.price * 1) / 10) * price;
          price =  (info.price * 1) / 10 * price;
        } else {
          chooseCouponPrice = info.price;
          price = price - info.price;
        }
        price = price > 0 ? price.toFixed(2) : '0.00';
      }
    
      chooseCouponPrice = (chooseCouponPrice * 1).toFixed(2);
      console.log("getAfterCouponPrice", price,chooseCouponPrice);
      this.setData({
        chooseCouponPrice: chooseCouponPrice
      })
      return price;
    },
    //积分抵扣后的价格
    getAfterPointsPrice(price) {
      console.log("getAfterPointsPrice",typeof(price))
      if (this.data.isCanUsePoint) {
        let goodsInfo = this.data.goodsInfo,
          basicInfo = this.data.basicInfo;
        let maxPointsDiscountPrice = 0;
        if(this.data.isVipPay){
          maxPointsDiscountPrice=price > goodsInfo.deductiblePoints * 1 ? goodsInfo.deductiblePoints : price; //价格大于
        }else{
          maxPointsDiscountPrice= price > goodsInfo.deductibleAmount * 1 ? goodsInfo.deductibleAmount : price; //价格大于
        }
        let pointToPirce = Math.floor(basicInfo.userPoints) / basicInfo.rmb2Points;
        //积分抵扣金额
        let pointsDiscountPirce = pointToPirce > maxPointsDiscountPrice ? maxPointsDiscountPrice : pointToPirce;
        //使用的积分数量
        let userPointNum = pointsDiscountPirce * basicInfo.rmb2Points;
        userPointNum = pointToPirce > maxPointsDiscountPrice ? Math.ceil(userPointNum) : Math.floor(userPointNum);
        this.setData({
          pointDiscountText: `使用${userPointNum}积分抵扣${(pointsDiscountPirce * 1).toFixed(2)}元`
        })
        if(this.data.isChooseUsePoint){
          price = price - pointsDiscountPirce;
          price = price > 0 ? price.toFixed(2) : '0.00';
        }
        console.log("getAfterPointsPrice", `price:${price}`);
      }
      return price;
    },
    getVipDisPriceInfo() {
      let goodsInfo = this.data.goodsInfo,
        basicInfo = this.data.basicInfo;
      let res = "";
      if (basicInfo.vipType == 2) {
        //vip身份
        if (goodsInfo.vipDiscountType == 1) {
          //折扣
          if (basicInfo.vipDiscount && basicInfo.vipDiscount != 100) {
            res = {
              vipType: 2,
              dpType: 1,
              dpVal: basicInfo.vipDiscount,
              tit: `VIP折扣(${(basicInfo.vipDiscount / 10).toFixed(2)}折)`,
              val: "￥" + (goodsInfo.price * basicInfo.vipDiscount / 100).toFixed(2)
            }
          }
        } else {
          //价格
          if (goodsInfo.vipDiscountPrice) {
            res = {
              vipType: 2,
              dpType: 2,
              dpVal: goodsInfo.vipDiscountPrice * 1,
              tit: "VIP价格",
              val: "￥" + goodsInfo.vipDiscountPrice
            }
          }
        }
      } else if (basicInfo.vipType == 4) {
        //svip身份
        if (goodsInfo.vipDiscountType == 1) {
          //折扣
          if (basicInfo.svipDiscount && basicInfo.svipDiscount != 100) {
            res = {
              vipType: 4,
              dpType: 1,
              dpVal: basicInfo.svipDiscount,
              tit: `SVIP折扣(${(basicInfo.svipDiscount / 10).toFixed(2)}折)`,
              val: "￥" + (goodsInfo.price * basicInfo.svipDiscount / 100).toFixed(2)
            }
          }
        } else {
          //价格
          if (goodsInfo.svipDiscountPrice) {
            res = {
              vipType: 4,
              dpType: 2,
              dpVal: goodsInfo.svipDiscountPrice * 1,
              tit: "VIP价格",
              val: "￥" + goodsInfo.svipDiscountPrice
            }
          }
        }
      } else if(basicInfo.vipType > 1){
        if (basicInfo.agentDiscount && basicInfo.agentDiscount != 100) {
          res = {
            vipType: basicInfo.vipType,
            dpType: 1,
            dpVal: basicInfo.agentDiscount,
            tit: "服务商折扣",
            val: "￥" + (goodsInfo.price * basicInfo.agentDiscount / 100).toFixed(2)
          }
        }
      }
      console.log("vipDisPriceInfo", res || '不是会员，没有会员价')
      return res;
    },
    //能否使用优惠券
    isCanUseCoupon() {
      let flag = false;
      let isVipPay = this.data.isVipPay,
          params = this.data.params,
          goodsInfo = this.data.goodsInfo;
      //非拼团且优惠券存在
      if (params.relationType != config.relationTypeMap.collage && params.relationType != config.relationTypeMap.flashSales && this.data.basicInfo.coupon.enable.length) {
        if(isVipPay){
          //新人价、续费折扣不支持积分抵扣和使用优惠券
          if((goodsInfo.isNewUser == 1 && goodsInfo.newUserPrice) ||((goodsInfo.renewRate / 100).toFixed(4) != 1 && goodsInfo.isSetRenew == 1 && goodsInfo.isNewUser == 0 && goodsInfo.isRenew == 1)){
            flag = false;
          }else{
            flag = true;
          }
        }else{
          flag = true;
        }
      }
      console.log("isCanUseCoupon", flag)
      return flag;
    },
    /**
     * @description:能够使用积分
     * @param {Number} price 
     * @return {Number} price
     *  对于限时购和拼团直接不能使用积分的
     *  vip和svip新人价、续费折扣不支持积分抵扣
     * 
     */
    //能够使用积分
    isCanUsePoint(price) {
      //积分抵扣  并且开启积分抵扣，并且有设置积分和金额的比例,并且用户积分大于0，并且可抵扣金额大于0，并且不是购买vip和svip的时候才显示   限时购不可使用积分
      let flag = false;
      let basicInfo = this.data.basicInfo,
        goodsInfo = this.data.goodsInfo,
        relationType = this.data.params.relationType,
        relationTypeMap = config.relationTypeMap,
        ckFrom = this.data.params.ckFrom,
        ckFromDict = config.ckFrom;
      //开启积分抵扣 && 有设置积分和金额的比例 && 用户积分大于0 && 可抵扣金额大于0(vip-deductiblePoints 其他-deductibleAmount)
      if (basicInfo.enablePoints && basicInfo.rmb2Points && Number(basicInfo.userPoints) > 0 && (Number(goodsInfo.deductibleAmount) > 0 || Number(goodsInfo.deductiblePoints) > 0)) {
        if (relationType != relationTypeMap.collage && relationType != relationTypeMap.flashSales && ckFrom != ckFromDict.collageVip && ckFrom != ckFromDict.collageSvip) {
          //总积分/1元所需要的积分=可以抵扣多少元(x积分抵扣1元)
          if (goodsInfo.price >= 1 && price >= 1 && Math.floor(basicInfo.userPoints / basicInfo.rmb2Points) >= 1) {
            if(this.data.isVipPay){
              console.log("yyyyy")
              //新人价、续费折扣不支持积分抵扣和使用积分抵扣
              if((goodsInfo.isNewUser == 1 && goodsInfo.newUserPrice) ||((goodsInfo.renewRate / 100).toFixed(4) != 1 && goodsInfo.isSetRenew == 1 && goodsInfo.isNewUser == 0 && goodsInfo.isRenew == 1)){
                flag = false;
              }else{
                flag = true;
              }
            }else{
              flag = true;
            }
          }
        }
      }
      console.log("isCanUsePoint", flag);
      return flag;
    },

    // 并且开启积分抵扣，并且有设置积分和金额的比例,并且用户积分大于0，并且可抵扣金额大于0，并且不是购买vip和svip的时候才显示   限时购不可使用积分
    openCouponList() {
      this.setData({
        isShowCouponList: true
      })
    },
    chooseCoupon(e) {
      let data = e.detail;
      let price = this.getAfterVipDiscountPrice(this.data.goodsInfo.price * 1);
      console.log("chooseCoupon", data);
      if (data && data.type == 3) {
        if (data.amount * 1 > 0 && data.amount * 1 > price) {
          wx.showToast({
            title: '购买金额未达到要求，不可使用！',
            icon: "none",
            duration: 2500
          });
          return;
        }
      }
      this.setData({
        chooseCouponInfo: data
      }, () => {
        this.calcProPrice();
      });
    },







    // 会员折扣率,抄coursePay逻辑的，如果是服务商 就不需要购买会员，所以计算的时候服务商优先
    /**
     * 1-普通会员 
          2-VIP 
          3-代理商 
          4-SVIP 
          5-合伙人，
          6-分公司，
          7运营中心，
          8总代, 
          9 agent6, 
          10 agent7, 
          11 agent8, 
          12 agent9
    */
    // getVipDis() {
    //   let vipType = this.data.basicInfo.vipType,
    //     goodsInfo = this.data.goodsInfo,
    //     basicInfo = this.data.basicInfo;
    //   let discountRate = 1;
    //   //服务商身份是否有折扣(非普通人，非VIP, 非svip)
    //   let isAgentHasDis = vipType != 1 && vipType != 2 && vipType != 4 && basicInfo.agentDiscount && Number(basicInfo.agentDiscount) < 100;
    //   if (goodsInfo.vipDiscountType == 2 && !isAgentHasDis) {
    //     //价格折扣当前是服务商身份没有折扣设置，直接返回1（不管svip和vip身份的
    //     return discountRate;
    //   }

    //   let permission = goodsInfo.permission;
    //   if (isShowAgent) {
    //     discountRate = Number(basicInfo.agentDiscount / 100).toFixed(4);
    //   } else if (permission == 17 && vipType == 2) {
    //     discountRate = Number(basicInfo.vipDiscount / 100).toFixed(4);
    //     this.vipDiscountInfo = {
    //       title: `VIP(${(basicInfo.vipDiscount / 10).toFixed(2)}折)`
    //     };
    //   } else if (permission == 20 && vipType == 4) {
    //     discountRate = Number(basicInfo.svipDiscount / 100).toFixed(4);
    //     this.vipDiscountInfo = {
    //       title: `SVIP(${(basicInfo.svipDiscount / 10).toFixed(2)}折)`
    //     };
    //   }
    //   // console.log("getVipDis", getVipDis)
    //   return discountRate;
    // },

    //获取积分抵扣的文本信息
    getUserPointTxt() {

    },



  }
})